package com.imooc.bilibili.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.imooc.bilibili.domain.exception.ConditionException;

import java.util.Calendar;
import java.util.Date;

/**
 * ProjectName imooc-bilibili
 *
 * @author xieyucan
 * <br>CreateDate 2022/10/22 14:13
 */
public class TokenUtil {

    private static final String ISSUER="谢钰灿";
    public static String generateToken(Long userId) throws Exception {
        //创建算法
        Algorithm algorithm=Algorithm.RSA256(RSAUtil.getPublicKey(),RSAUtil.getPrivateKey());
        //生成时间，以便以后期设置过期时间
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        //当前时间+过期时间
        calendar.add(Calendar.DAY_OF_MONTH,1);
        //生成token   JWT+create+主键+签发者+过期时间+根据算法生成jwt
        return JWT.create().withKeyId(String.valueOf(userId))
                .withIssuer(ISSUER)
                .withExpiresAt(calendar.getTime())
                .sign(algorithm);
    }


    public static Long verifyToken(String token)
    {
        try {
            Algorithm algorithm=Algorithm.RSA256(RSAUtil.getPublicKey(),RSAUtil.getPrivateKey());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            String userId=decodedJWT.getKeyId();
            return Long.valueOf(userId);
        }catch (TokenExpiredException e){
            throw new ConditionException("555","token过期!");
        }catch (Exception e){
            throw new ConditionException("非法用户token");
        }

    }
}
